package com.lzx.adx.report.task;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.lzs.adx.commmon.constant.RedisCacheKey;
import com.lzs.adx.commmon.redis.RedisUtils;
import com.lzx.adx.report.cache.OcpxAccountLocalCache;
import com.lzx.adx.report.cache.ProductConfigLocalCache;
import com.lzx.adx.report.dto.OcpxAccountDTO;
import com.lzx.adx.report.dto.ProductConfigDTO;
import com.lzx.adx.report.dto.ReportDTO;
import com.lzx.adx.report.service.ReportService;
import com.lzx.adx.report.support.context.v3.CallBackV3Context;
import com.lzx.adx.report.support.strategy.v3.media.AbstractChannel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;


@Component
@RestController
@RequestMapping("/vir")
@Slf4j
public class VirTualResultCallbackTask implements ITask{

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private CallBackV3Context callBackV3Context;

    @Autowired
    private ReportService reportService;

    /**
     * 虚拟上报回传
     * @param params   参数，多参数使用JSON数据
     * @throws Exception
     */
    @RequestMapping("/callback")
    @Override
    public void run(String params) throws Exception {
        log.info("开始执行虚拟回传的调度任务");
        //查询要跑虚拟的账户列表
        Set<Object> cacheSet = redisUtils.getCacheSet(RedisCacheKey.VIRTUAL_ACCOUNT_DSPID);
        if(CollectionUtil.isEmpty(cacheSet)){return;}
        cacheSet.forEach(item -> {
            //查询每个账户要跑的数据
            String key = String.format(RedisCacheKey.VIRTUAL_RESULT_CALLBACK_ACCOUNT,item.toString());
            List<Object> list = redisUtils.getList(key);
            if(CollectionUtil.isEmpty(list)){return;}

            List<String> removeDataList=new CopyOnWriteArrayList();
            for (Object item1 : list) {


                //1.把转换结果更新到数据库
                String bizRequestId =item1.toString();
             try {

               log.info("[虚拟回传任务]正在执行 账户号{}，流水ID{}",item.toString(),bizRequestId);
                Map<String, Object> p = new HashMap<>();
                p.put("bizRequestId", bizRequestId);
                List<ReportDTO> listt = reportService.list(p);
                ReportDTO reportDTO;
                if (CollectionUtil.isNotEmpty(listt)) {
                    reportDTO = listt.get(0);
                } else {
                    log.error("[虚拟回传任务]虚拟回传异步任务-当前流水号{}，系统当前不存在",bizRequestId);
                    return;
                }


                OcpxAccountDTO accountDTO = OcpxAccountLocalCache.getInstance().get(item.toString());
                String defaultKey = accountDTO.getDefaultKey();
                String time = String.valueOf(System.currentTimeMillis());
                AbstractChannel abstractReport = callBackV3Context.getCallBack(accountDTO.getMediaChannel());
                abstractReport.callback(reportDTO, accountDTO, defaultKey, time);

                //移除要跑的数据
                log.info("[虚拟回传任务]移除前的list大小{}， 移除的数据为",list.size(),bizRequestId);
                 removeDataList.add(bizRequestId);
                log.info("移除后的的list大小{}",list.size());
                }catch (Exception e){
                    log.error("[虚拟回传任务]执行虚拟回传有点的问题，问题错误为{}",e);
                }
            }

            removeDataList.forEach(c->{
                redisUtils.removeValueFromList(key,c);
            });
            //帮助回收
            removeDataList=null;
        });
    }
}
